// import { onMessage } from 'webext-bridge/content-script'
import { createApp } from 'vue'
import App from './views/App.vue'
import { setupApp } from '~/logic/common-setup'
import { authSyncManager } from '~/logic/auth-sync'
import { ENV } from '~/env'

// Firefox `browser.tabs.executeScript()` requires scripts return a primitive value
(() => {
  // 例如只在 https://app.example.com* 这类页面同
  // 获取 env 的配置
  const needAuthSync = location.hostname.endsWith(ENV.LOGIN_DOMAIN)
  if (needAuthSync)
    authSyncManager.triggerSync()

  // communication example: send previous tab title from background page
  // onMessage('tab-prev', ({ data }) => {

  // })

  // mount component to context window
  const container = document.createElement('div')
  container.id = __NAME__
  const root = document.createElement('div')
  const styleEl = document.createElement('link')
  const shadowDOM = container.attachShadow?.({ mode: __DEV__ ? 'open' : 'closed' }) || container
  styleEl.setAttribute('rel', 'stylesheet')
  styleEl.setAttribute('href', browser.runtime.getURL('dist/contentScripts/style.css'))
  shadowDOM.appendChild(styleEl)
  shadowDOM.appendChild(root)
  document.body.appendChild(container)
  // console.log('[vitesse-webext] Container mounted')

  const app = createApp(App)
  setupApp(app)
  app.mount(root)
  // console.log('[vitesse-webext] Vue app mounted')
})()
